/**
 * Created by caoshun on 2025/6/6.
 */

import Logo from '@/assets/images/logo.png';
import { LOCAL, SESSION } from '@/constants/publicConstant';
import useIntlCustom from '@/hooks/useIntlCustom';
import { getUserPermisson, login } from '@/services/login';
import {
  ArrowLeftOutlined,
  ArrowRightOutlined,
  EyeInvisibleOutlined,
  EyeTwoTone,
  LockOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { Button, Form, Input, notification, Select } from 'antd';
import Cookies from 'js-cookie';
import { useCallback, useEffect, useState } from 'react';
import styles from './index.css';

const cname = Cookies.get('userId') || '';
const crole = Cookies.get('roleId') || '';
const cstation = Cookies.get('positionId') || '';
const inputStyle = { width: '320px' };

export default function Login() {
  const { translate } = useIntlCustom();
  const prefix = 'systemManage';

  // 状态管理
  const [currentStep, setCurrentStep] = useState(0); // 0: 用户名密码, 1: 角色岗位选择
  const [loading, setLoading] = useState(false);
  const [nextLoading, setNextLoading] = useState(false);
  const [roleOptions, setRoleOptions] = useState([]);
  const [stationOptions, setStationOptions] = useState([]);
  const [form] = Form.useForm();
  const [roleForm] = Form.useForm();

  // 初始化表单数据
  useEffect(() => {
    form.setFieldsValue({
      userId: cname,
      password: '',
      remember: !!cname,
    });
  }, [form]);

  // 第一步：验证用户名密码
  const handleNext = useCallback(() => {
    form
      .validateFields(['userId', 'password'])
      .then(async (values) => {
        setNextLoading(true);
        try {
          const result = await login();
          const token = result?.token;
          if (token) {
            sessionStorage.setItem(SESSION.token, token);
            setRoleOptions(
              result.roles?.map((item: { roleName: string; id: string }) => ({
                label: item.roleName,
                value: item.id,
              })) || [],
            );
            setStationOptions(
              result.positions?.map((item: { positionName: string; id: string }) => ({
                label: item.positionName,
                value: item.id,
              })) || [],
            );

            // 设置默认值
            roleForm.setFieldsValue({
              ...(crole && { roleId: crole }),
              ...(cstation && { positionId: cstation }),
            });

            // 触发滑动动画 - 确保状态更新
            setTimeout(() => {
              setCurrentStep(1);
            }, 100);
          } else {
            notification.error({ message: translate(prefix, 'error.invalid') });
          }
        } catch (e) {
          notification.error({ message: translate(prefix, 'error.invalid') });
        } finally {
          setNextLoading(false);
        }
      })
      .catch(() => {
        setNextLoading(false);
      });
  }, [form, translate, prefix, roleForm]);

  // 第二步：完成登录
  const handleLogin = useCallback(() => {
    roleForm
      .validateFields()
      .then(async (roleValues) => {
        const formValues = form.getFieldsValue();
        const finalValues = {
          ...formValues,
          ...roleValues,
          orgNo: '156',
          token: sessionStorage.getItem(SESSION.token),
        };

        setLoading(true);
        try {
          const res = await getUserPermisson();
          if (res) {
            sessionStorage.setItem(SESSION.codeIndex, 'user');
            localStorage.setItem(LOCAL.USER_PERMISSION, JSON.stringify(res));

            // 记住我逻辑
            if (finalValues.remember) {
              Cookies.set('userId', finalValues.userId);
              Cookies.set('roleId', finalValues.roleId);
              Cookies.set('positionId', finalValues.positionId);
            } else {
              Cookies.remove('userId');
              Cookies.remove('roleId');
              Cookies.remove('positionId');
            }

            window.location.href = '/demo';
          } else {
            sessionStorage.removeItem(SESSION.token);
            sessionStorage.removeItem(SESSION.codeIndex);
            localStorage.removeItem(LOCAL.USER_PERMISSION);
            notification.error({ message: translate(prefix, 'error.invalid') });
          }
        } catch (e) {
          sessionStorage.removeItem(SESSION.token);
          sessionStorage.removeItem(SESSION.codeIndex);
          localStorage.removeItem(LOCAL.USER_PERMISSION);
          notification.error({ message: translate(prefix, 'error.invalid') });
        } finally {
          setLoading(false);
        }
      })
      .catch(() => {
        setLoading(false);
      });
  }, [roleForm, form, translate, prefix]);

  // 返回上一步
  const handleBack = useCallback(() => {
    setCurrentStep(0);
  }, []);

  // 支持回车键
  const handleKeyPress = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === 'Enter') {
        if (currentStep === 0) {
          handleNext();
        } else {
          handleLogin();
        }
      }
    },
    [currentStep, handleNext, handleLogin],
  );

  return (
    <div className={styles.login}>
      <div className={styles.loginWrapper}>
        <div className={styles.loginHeader}>
          <div className={styles.logo}>
            <img alt="logo" src={Logo} />
          </div>
          <h1>{translate(prefix, 'title')}</h1>
          <p>{translate(prefix, 'loginDescription')}</p>
        </div>

        <div className={styles.loginContainer}>
          <div
            className={styles.stepContainer}
            style={{
              transform: `translateX(-${currentStep * 50}%)`,
              transition: 'transform 0.8s cubic-bezier(0.4, 0, 0.2, 1)',
            }}
          >
            {/* 第一步：用户名密码 */}
            <div className={styles.step}>
              <div className={styles.loginCard}>
                <div className={styles.cardHeader}>
                  <h2>Welcome Back</h2>
                  <div className={styles.stepIndicator}>
                    {translate(prefix, 'step')} 1/2 - {translate(prefix, 'credentials')}
                  </div>
                </div>

                <Form form={form} layout="vertical" className={styles.loginForm} onKeyDown={handleKeyPress}>
                  <Form.Item
                    name="userId"
                    label={translate(prefix, 'username')}
                    rules={[
                      { required: true, message: translate(prefix, 'validation.username.required') },
                      { max: 30, message: translate(prefix, 'validation.username.max') },
                    ]}
                  >
                    <Input
                      size="large"
                      allowClear
                      placeholder={translate(prefix, 'username.placeholder')}
                      prefix={<UserOutlined className={styles.inputIcon} />}
                      className={styles.loginInput}
                      autoComplete="username"
                    />
                  </Form.Item>

                  <Form.Item
                    name="password"
                    label={translate(prefix, 'password')}
                    rules={[
                      { required: true, message: translate(prefix, 'validation.password.required') },
                      { max: 30, message: translate(prefix, 'validation.password.max') },
                      { min: 6, message: translate(prefix, 'validation.password.min') },
                    ]}
                  >
                    <Input.Password
                      size="large"
                      placeholder={translate(prefix, 'password.placeholder')}
                      prefix={<LockOutlined className={styles.inputIcon} />}
                      iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                      className={styles.loginInput}
                      autoComplete="current-password"
                    />
                  </Form.Item>

                  <Button
                    type="primary"
                    size="large"
                    loading={nextLoading}
                    onClick={handleNext}
                    className={styles.nextButton}
                    icon={<ArrowRightOutlined />}
                    iconPosition="end"
                    block
                  >
                    {nextLoading ? translate(prefix, 'button.validating') : translate(prefix, 'button.next')}
                  </Button>
                </Form>
              </div>
            </div>

            {/* 第二步：角色岗位选择 */}
            <div className={styles.step}>
              <div className={styles.loginCard}>
                <div className={styles.cardHeader}>
                  <h2>{translate(prefix, 'roleSelection')}</h2>
                  <div className={styles.stepIndicator}>
                    {translate(prefix, 'step')} 2/2 - {translate(prefix, 'roleSelection')}
                  </div>
                </div>

                <Form form={roleForm} layout="vertical" className={styles.loginForm} onKeyDown={handleKeyPress}>
                  <Form.Item
                    name="roleId"
                    label={translate(prefix, 'roleId')}
                    rules={[{ required: true, message: translate(prefix, 'roleId.placeholder') }]}
                  >
                    <Select
                      size="large"
                      allowClear
                      placeholder={translate(prefix, 'roleId.placeholder')}
                      options={roleOptions}
                      className={styles.loginSelect}
                    />
                  </Form.Item>

                  <Form.Item
                    name="positionId"
                    label={translate(prefix, 'positionId')}
                    rules={[{ required: true, message: translate(prefix, 'positionId.placeholder') }]}
                  >
                    <Select
                      size="large"
                      allowClear
                      placeholder={translate(prefix, 'positionId.placeholder')}
                      options={stationOptions}
                      className={styles.loginSelect}
                    />
                  </Form.Item>

                  <div className={styles.buttonGroup}>
                    <Button
                      size="large"
                      onClick={handleBack}
                      className={styles.backButton}
                      icon={<ArrowLeftOutlined />}
                    >
                      {translate(prefix, 'button.back')}
                    </Button>

                    <Button
                      type="primary"
                      size="large"
                      loading={loading}
                      onClick={handleLogin}
                      className={styles.loginButton}
                    >
                      {loading ? translate(prefix, 'button.loading') : translate(prefix, 'button.login')}
                    </Button>
                  </div>
                </Form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
